<!--
 * @Descripttion: 商品库权限管理
 * @version:
 * @Author: 赵致喜
 * @Date: 2020-10-13 16:03:00
 * @LastEditors: 赵致喜
 * @LastEditTime: 2020-10-29 20:20:25
-->
<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="6">
        <el-tree :data="treeData"
                 :props="defaultProps"
                 :load="loadNode"
                 lazy
                 show-checkbox
                 ref="listTree"
                 node-key="categoryId"
                 class="listTree"
                 :style="leftTree"
                 @check-change="handleCheckChange">
        </el-tree>
      </el-col>
      <el-col :span="18">
        <div class="control-box">
          <!-- control 操作区 START -->
          <e-control :search-form-options="formOptions"
                     :search-label-width="searchLabelWidth"
                     :btns="btns"
                     @on-search="searchControlHandle"
                     @on-refresh="refreshControlHandle"
                     @change-height="changeControlHeight"
                     @on-approved="approvedControlHandle"
                     @on-suspend="typeChangeHandle(btns[2].title,'0')"
                     @on-adopt="typeChangeHandle(btns[1].title,'1')"
                     v-on="$listeners"></e-control>
          <!-- control 操作区 END -->
        </div>
        <div class="table-box">
          <!-- table 数据表格 START -->
          <e-table :data="tableData"
                   :columns="columns"
                   ref="multipleTable"
                   stripe
                   border
                   :maxHeight="tableMaxHeight"
                   style="width: 100%"
                   @selection-change="changeTableSelectData"
                   :current="pageData.current"
                   :total="pageData.total"
                   @page-size-change="changePageSize"
                   @page-current-change="changePageCurrent">
          </e-table>
          <!-- table 数据表格 END -->
        </div>
      </el-col>
    </el-row>
    <!-- editDialog 编辑弹窗 START -->
    <div v-if="editDialogShow">
      <el-dialog title="维护商品库授权"
                 :visible.sync="editDialogShow"
                 :close-on-click-modal="false"
                 :close-on-press-escape="false"
                 :before-close="closeDialog"
                 width="80%">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-tree :data="dialogTreeData"
                     :props="dialogDefaultProps"
                     :load="dialogLoadNode"
                     show-checkbox
                     :check-strictly="true"
                     ref="dialogTree"
                     node-key="id"
                     lazy
                     class="listTree"
                     style="height:700px;overflow-y: scroll;"
                     :default-expanded-keys="expandedKeys"
                     :default-checked-keys="checkedKeys"
                     @check-change="dialogHandleCheckChange">
            </el-tree>
            <!-- :default-expanded-keys="[2, 3]"
                     :default-checked-keys="[5]" -->
          </el-col>
          <el-col :span="18">
            <div class="control-box">
              <!-- control 操作区 START -->
              <e-control ref="searchMaintain"
                         :search-form-options="formOptions1"
                         :search-label-width="searchLabelWidth"
                         @on-search="supplierSearchHandle"
                         @on-refresh="refreshControlHandle"
                         @change-height="changeControlHeight"
                         @on-approved="approvedControlHandle"></e-control>
              <!-- control 操作区 END -->
            </div>
            <e-table :data="supplierTableData"
                     :columns="columns1"
                     stripe
                     border
                     :maxHeight="tableMaxHeight"
                     style="width: 100%"
                     :current="supplierPageData.current"
                     :total="supplierPageData.total"
                     @row-click="rowClickHandle"
                     :row-class-name="tableRowClassName"
                     @page-size-change="supplierChangePageSize"
                     @page-current-change="supplierChangePageCurrent">
            </e-table>
          </el-col>
        </el-row>
        <span slot="footer"
              class="dialog-footer">
        <el-button type="primary"
                   @click="saveDialogDataHandle">保存</el-button>
      </span>
      </el-dialog>
    </div>
    <!-- editDialog 编辑弹窗 END -->
  </div>
</template>

<script>
import eControl from '@/components/e-control'
import { getQueryItemTrees, getQueryMaintenanceAuthority, updateAuthorityStatus, getQuerySupplier, insertAuthority, getQueryItemTreesBySupplierId } from '@/api/admin.api'
import { formOptions, btns, formOptions1 } from './control'
import { columns, columns1 } from './columns'
export default {
  name: 'commodity-jurisdiction-manager',
  components: {
    eControl
  },
  props: {
  },
  data () {
    return {
      // 表格表头
      columns,
      // 上下架记录表格表头
      columns1,
      // 表单配置项
      formOptions,
      searchLabelWidth: '100px',
      // 按钮组
      btns,
      // 弹窗表单配置项
      formOptions1,
      // 授权表单数据
      formData: {},
      // 选中行数据
      rowData: {},
      // 左侧树样式
      leftTree: {
        'height': window.innerHeight - 100 + 'px',
        'overflowY': 'scroll'
      },
      // 左侧树
      treeData: [],
      // 树配置项
      defaultProps: {
        children: 'children',
        label: 'label',
        check: false,
        isLeaf: 'leaf',
        categorylevel: 1,
        categoryId: 'id'
      },
      // 弹窗树
      dialogTreeData: [],
      // 弹窗树配置项
      dialogDefaultProps: {
        children: 'children',
        label: 'label',
        level: 1,
        id: 'id',
        isLeaf: 'leaf'
      },
      // 选中树父级id
      expandedKeys: [],
      // 选中叶子节点id
      checkedKeys: [],
      // 供应商查询表单
      supplierSearchFormData: {},
      // 供应商数据
      supplierTableData: [],
      // 供应商分页数据
      supplierPageData: {
        // 当前分页
        current: 1,
        // 分页条数
        size: 10,
        // 数据总数
        total: 0
      },
      // 上传图片数据
      fileList: [],
      // 编辑框是否展示
      editDialogShow: false,
      editDialogType: 0,
      // 编辑框表单数据
      dialogFormCurrent: {},
      // 查询表单
      searchFormData: {},
      // 控制区高度
      controlHeight: 0,
      // 表格数据
      tableData: [],
      // 分页数据
      pageData: {
        // 当前分页
        current: 1,
        // 分页条数
        size: 10,
        // 数据总数
        total: 0
      },
      // 表格选中数据
      tableSelectData: [],
      // 获取当前行index
      getIndex: '',
      // 树禁用
      dialogTreeDisable: []
    }
  },
  watch: {},
  computed: {
    // 组合查询条件和分页
    searchData () {
      const { pageNum, pageSize } = this.pageData
      return { ...this.searchFormData, size: pageSize, current: pageNum }
      // return Object.assign(this.searchFormData,{size: pageSize},{current:pageNum})
    },
    // 表单实例
    dialogForm () {
      return this.$refs.dialogForm
    },
    // 表格最大高度
    tableMaxHeight () {
      return window.innerHeight - this.controlHeight - 160
    },
    // // 左侧树样式
    // leftTree () {
    //   return {
    //     'height': window.innerHeight - 160,
    //     'overflowY': 'scroll'
    //   }
    // },
    // 编辑框标题
    editDialogTitle () {
      return this.editDialogType === 0 ? '新增' : '编辑'
    },
    // 操作列自定义按钮
    operationBtn () {
      let btns
      this.tableColumns.map(item => {
        if (item.slotName === 'operation') {
          btns = item.btns || []
        }
      })
      return btns
    }
  },
  methods: {
    // 获取组织树
    getOrgTreeEvent () {
      getQueryItemTrees({ categorylevel: '1' }).then((res) => {
        const newArr = []
        res.map(item => {
          const obj = {}
          obj.label = item.category_name
          obj.categoryId = item.id
          obj.categorylevel = item.category_level + 1
          obj.check = item.check
          newArr.push(obj)
        })
        this.treeData = newArr
      })
    },

    // 懒加载左侧tree
    loadNode (node, resolve) {
      if (node.level === 1) {
        getQueryItemTrees({ categorylevel: node.data.categorylevel, categoryId: node.data.categoryId }).then((res) => {
          const secArr = []
          res.map(item => {
            const obj = {}
            obj.label = item.category_name
            obj.categoryId = item.id
            obj.categorylevel = item.category_level + 1
            obj.check = item.check
            secArr.push(obj)
          })
          return resolve(secArr)
        })
      }
      if (node.level === 2) {
        getQueryItemTrees({ categorylevel: node.data.categorylevel, categoryId: node.data.categoryId }).then((res) => {
          const thrArr = []
          res.map(item => {
            const obj = {}
            obj.label = item.category_name
            obj.categoryId = item.id
            obj.categorylevel = item.category_level + 1
            obj.check = item.check
            obj.leaf = true
            thrArr.push(obj)
          })
          return resolve(thrArr)
        })
      }
    },

    // 选择树节点
    handleCheckChange () {
      const ids = this.$refs['listTree'].getCheckedKeys()
      this.searchFormData.itemCategoryIds = ids.toString()
      this.getTableData()
    },

    // 初始化商品列表数据
    init () {
      this.getTableData()
    },
    // 列表查询
    searchControlHandle (data) {
      this.searchFormData = data
      this.refreshPageCurrent()
    },
    // 重置查询条件
    refreshControlHandle (data) {
      this.searchFormData = data
    },
    // 控制区高度计算
    changeControlHeight (height) {
      this.controlHeight = height
    },
    // 维护商品库授权弹窗
    approvedControlHandle () {
      this.openDialog()
    },
    // 获取选中数据
    changeTableSelectData (rows) {
      this.tableSelectData = rows
    },
    // 列表分页显示数
    changePageSize (size) {
      this.pageData.size = size
      this.getTableData()
    },
    // 当前分页页数
    changePageCurrent (current) {
      this.pageData.current = current
      this.getTableData()
    },
    // 重置当前分页
    refreshPageCurrent () {
      this.pageData.current = 1
      this.getTableData()
    },
    // 获取商品基本列表
    getTableData () {
      const newSearchFormData = { ...this.searchFormData, ...this.pageData }
      getQueryMaintenanceAuthority(newSearchFormData).then(res => {
        this.tableData = res.records
        this.pageData.total = res.total
      })
    },
    // 修改商品库权限状态
    typeChangeHandle (title, type) {
      const ids = []
      this.tableSelectData.map(item => {
        ids.push(item.id)
      })
      if (ids.length > 0) {
        this.$confirm(`确定要${title}权限吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateAuthorityStatus({ authorityId: ids.toString(), status: type }).then(res => {
            this.$message({
              type: 'success',
              message: `${title}成功`
            })
            this.getTableData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })

      } else {
        this.$alert(`请选择要${title}的数据`, '提示', {
          confirmButtonText: '确定',
          showClose: false
        })
      }
    },
    // 授权树节点选择
    dialogHandleCheckChange () {
      const ids = this.$refs['dialogTree'].getCheckedKeys()
      this.formData.itemCategoryId = ids
    },
    // 授权弹窗显示
    openDialog () {
      this.getDialogTree()
      this.querySupplier()
      this.editDialogShow = true
    },
    // 弹窗左侧树请求数据
    getDialogTree () {
      getQueryItemTreesBySupplierId().then((res) => {
        const dialogNewArr = []
        res.map(item => {
          const obj = {}
          obj.label = item.category_name
          obj.id = item.id
          obj.level = item.category_level
          obj.children = []
          dialogNewArr.push(obj)
        })
        this.dialogTreeData = dialogNewArr
      })
    },
    // 弹窗懒加载左侧tree
    dialogLoadNode (node, resolve) {
      const childArr = []
      if (node.data.level === 1) {
        node.data.show = true
        getQueryItemTreesBySupplierId({ categoryId: node.data.id }).then((res) => {
          res[0].children.map(item => {
            const level2 = {}
            level2.label = item.category_name
            level2.id = item.id
            level2.level = item.category_level
            level2.children = []
            item.children.map(item1 => {
              const level3 = {}
              level3.label = item1.category_name
              level3.id = item1.id
              level3.leaf = true
              level3.level = item1.category_level
              level3.priceFloat = item1.price_float
              level2.children.push(level3)
            })
            childArr.push(level2)
            return resolve(childArr)
          })
        })
      }
      if (node.data.level === 2) {
        node.data.children.map(item => {
          this.dialogTreeDisable.map(sitem => {
            if (item.id === sitem) {
              item.disabled = true
            }
          })
        })
        return resolve(node.data.children)
      }
    },

    // 供应商查询数据
    supplierSearchHandle (data) {
      this.supplierSearchFormData = data
      this.supplierRefreshPageCurrent()
    },
    // 供应商列表分页显示数
    supplierChangePageSize (size) {
      this.supplierPageData.size = size
      this.querySupplier()
    },
    // 供应商当前分页页数
    supplierChangePageCurrent (current) {
      this.supplierPageData.current = current
      this.querySupplier()
    },
    // 供应商重置当前分页
    supplierRefreshPageCurrent () {
      this.supplierPageData.current = 1
      this.getIndex = ''
      this.rowData = {}
      this.querySupplier()
    },
    // 获取供应商数据
    querySupplier () {
      const newSupplierSearch = { ...this.supplierSearchFormData, ...this.supplierPageData }
      getQuerySupplier(newSupplierSearch).then(res => {
        this.supplierTableData = res.records
        this.supplierPageData.total = res.total
      })
    },
    // 关闭授权弹窗
    closeDialog () {
      this.editDialogShow = false
      this.refreshDialogData()
    },
    // 初始化弹窗数据
    refreshDialogData () {
      this.rowData = {}
      this.supplierSearchFormData = {}
      this.getIndex = ''
      // this.dialogTreeData = []
      this.expandedKeys = []
      this.checkedKeys = []
    },
    // 选中行数据
    rowClickHandle (row) {
      this.refreshDialogData()
      this.getIndex = row.index
      this.rowData = row
      this.dialogTreeDisable = []
      getQueryItemTreesBySupplierId({ supplierId: row.id }).then((res) => {
        if (res === null) {
          this.getDialogTree()
          return false
        }
        this.getDialogTree()
        res.map(item => {
          this.expandedKeys.push(item.id)
          this.dialogTreeData.map(item1 => {
            // 匹配一级树ID与返回ID
            if (item.id === item1.id) {
              const childArrs = []
              // 循环二级菜单
              item.children.map(item2 => {
                const dialogLevel2 = {}
                dialogLevel2.label = item2.category_name
                dialogLevel2.id = item2.id
                dialogLevel2.level = item2.category_level
                dialogLevel2.children = []
                // 循环三级菜单
                item2.children.map(item3 => {
                  const dialogLevel3 = {}
                  dialogLevel3.label = item3.category_name
                  dialogLevel3.id = item3.id
                  dialogLevel3.level = item3.category_level
                  dialogLevel3.pid = item3.parent_category_id
                  dialogLevel3.check = item3.check
                  dialogLevel3.disabled = item3.check
                  dialogLevel2.children.push(dialogLevel3)
                  if (item3.check) {
                    this.dialogTreeDisable.push(item3.id)
                    this.expandedKeys.push(item3.parent_category_id)
                    this.checkedKeys.push(item3.id)
                  }
                })
                // 父级ID去重
                this.expandedKeys = [...new Set(this.expandedKeys)]
                // 插入子级数据
                childArrs.push(dialogLevel2)
              })
            }
          })
        })
      })
    },
    // 绑定对应对应class
    tableRowClassName ({ row, rowIndex }) {
      row.index = rowIndex
      if ((this.getIndex) === rowIndex) {
        return 'active-td'
      }
    },
    // 保存授权信息
    saveDialogDataHandle () {
      if (this.getIndex === '') {
        this.$message({
          message: '至少选择一条数据',
          type: 'warning'
        })
        return false
      }
      // 取已存数据差集
      const mergeIds = [...this.formData.itemCategoryId].filter(x => [...this.checkedKeys].every(y => y !== x))
      const newFormData = {
        itemCategoryId: mergeIds.toString(),
        supplierCode: this.rowData.CODE,
        supplierId: this.rowData.id,
        supplierName: this.rowData.NAME
      }
      insertAuthority(newFormData).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.closeDialog()
        this.getTableData()
      })
    }
  },
  created () { },
  mounted () {
    this.getOrgTreeEvent()
    this.init()
  }
}
</script>
<style lang="scss">
.control-box {
  margin-bottom: 10px;
}
.text-right {
  text-align: right;
}
.pd5 {
  padding: 5px;
}
.listTree .el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
    display: inline-block;
  }

  .el-checkbox__input > .el-checkbox__inner {
    display: none;
  }
}
.active-td td {
  background-color: #cae1ff !important;
}
</style>
